package util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JdbcUtil {
    static Connection connection=null;
    static PreparedStatement statement=null;
    static ResultSet resultSet=null;
    static ResultSetMetaData resultSetMetaData=null;


    private static Connection getConnection(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://192.168.77.100:3306/travel_db?characterEncoding=utf-8", "root", "123456");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }
    static void closeSrc(){
        try {
            if (resultSet!=null)
                resultSet.close();
            if (statement!=null)
                statement.close();
            if (connection!=null)
                connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static <E> List<Map<String,Object>>selectBySql(String sql,E...e){
        List<Map<String,Object>>list=new ArrayList<>();
        try {
            connection=getConnection();
            statement=connection.prepareStatement(sql);
            for (int i = 0; i < e.length; i++) {
                statement.setObject(i+1,e[i]);
            }
            resultSet=statement.executeQuery();
            resultSetMetaData=resultSet.getMetaData();
            while (resultSet.next()){
                Map<String,Object>map=new HashMap<>();
                for (int i = 1 ; i <= resultSetMetaData.getColumnCount(); i++) {
                    map.put(resultSetMetaData.getColumnName(i),resultSet.getObject(i));
                }
                list.add(map);
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }finally {
            closeSrc();
        }
        return list;
    }
    public static <E> int editBySql(String sql,E...e){
        connection=getConnection();
        int result=0;
        try {
            statement=connection.prepareStatement(sql);
            for (int i = 0; i < e.length; i++) {
                statement.setObject(i+1,e[i]);
            }
            result=statement.executeUpdate();
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }finally {
            closeSrc();
        }
        return result;
    }
}
